package com.uduemc.biso.node.web.api.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.uduemc.biso.core.extities.center.SysApiAccess;
import com.uduemc.biso.node.web.api.component.SpringContextUtils;
import com.uduemc.biso.node.web.api.service.ApiaccessService;
import com.uduemc.biso.node.web.utils.IpUtil;

@Component
public class ApiServiceInterceptor implements HandlerInterceptor {

	private static final Logger logger = LoggerFactory.getLogger(ApiServiceInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

		String ipAddr = IpUtil.getIpAddr(request);
		ApiaccessService apiaccessServiceImpl = SpringContextUtils.getBean("apiaccessServiceImpl", ApiaccessService.class);
		List<SysApiAccess> listSysApiAccess = apiaccessServiceImpl.getOkallowAccessMaster();
		if (!CollectionUtils.isEmpty(listSysApiAccess)) {
			for (SysApiAccess sysApiAccess : listSysApiAccess) {
				String ipaddress = sysApiAccess.getIpaddress();
				if (ipaddress.equals(ipAddr)) {
					return true;
				}
			}
		}

		logger.info("ip not access, access ip: " + ipAddr + " server ip address: " + listSysApiAccess);
		return false;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

	}

}
